package qjc.l_栈;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;


public class l3_字符串解码 {
    public String decodeString(String s) {
        Deque<Integer> num = new ArrayDeque<>();
        Deque<String> str = new ArrayDeque<>();
        StringBuilder sb = new StringBuilder();
        int curNum = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                curNum = curNum * 10 + (c - '0');
            } else if (c == '[') {
                num.push(curNum);
                str.push(sb.toString());
                sb = new StringBuilder();
                curNum = 0;
            } else if (c == ']') {
                int k = num.pop();
                String preStr = str.pop();
                String repeatedStr = repeatString(sb.toString(), k);
                sb = new StringBuilder(preStr).append(repeatedStr);
            }else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private String repeatString(String sb, int k) {
        if (k == 0 || sb.length() == 0 || sb == null) {
            return "";
        }
        StringBuilder sb2 = new StringBuilder();
        for (int i = 0; i < k; i++) {
            sb2.append(sb);
        }
        return sb2.toString();
    }
}
